﻿using System;

namespace DataStructure
{
    public class DoubleLinkedList
    {
        private Node head;
        private Node tail;
        private int size;

        public DoubleLinkedList()
        {
            head = null;
            tail = null;
            size = 0;
        }

        private class Node
        {
            public int Data;
            public Node Next;
            public Node Previous;

            public Node(int data)
            {
                Data = data;
                Next = null;
                Previous = null;
            }
        }

        public void Add(int data)
        {
            Node newNode = new Node(data);

            if (head == null)
            {
                head = newNode;
                tail = newNode;
            }
            else
            {
                tail.Next = newNode;
                newNode.Previous = tail;
                tail = newNode;
            }

            size++;
        }

        public void Insert(int data, int index)
        {
            if (index < 0 || index > size) throw new IndexOutOfRangeException("索引超出范围");

            Node newNode = new Node(data);

            if(index == 0)
            {
                newNode.Next = head;
                head.Previous = newNode;
                head = newNode;
            }
            else if (index == size)
            {
                Add(data);
            }
            else
            {
                Node current = head;

                for (int i = 0; i < index; i++)
                {
                    current = current.Next;
                }

                newNode.Previous = current.Previous;
                current.Previous.Next = newNode;
                newNode.Next = current;
                current.Previous = newNode;
            }

            size++;
        }

        public void Delete(int index)
        {
            if (index < 0 || index >= size) throw new IndexOutOfRangeException("索引超出范围");

            if(index == 0)
            {
                if (head == tail)
                {
                    head = null;
                    tail = null;
                }
                else
                {
                    head = head.Next;
                    head.Previous = null;
                }
            }
            else if (index == size - 1)
            {

            }
        }
    }
}